<template>
	<view class="history-container">
		<!-- 标题 -->
		<view class="header">
			<text class="title">历史表扬榜</text>
			<text class="subtitle">记录学生的点滴进步</text>
		</view>

		<!-- 日期选择卡片 -->
		<scroll-view scroll-x class="date-scroll" :scroll-into-view="'date-'+activeDateIndex">
			<view class="date-cards">
				<view v-for="(date, index) in dateList" :key="index" :id="'date-'+index" class="date-card"
					:class="{active: activeDateIndex === index}" @click="changeDate(index)"
					:animation="dateCardAnim[index]">
					<text class="day">{{ formatDay(date) }}</text>
					<text class="weekday">{{ formatWeekday(date) }}</text>
					<text class="date">{{ formatDate(date) }}</text>
				</view>
			</view>
		</scroll-view>

		<!-- 表扬记录列表 -->
		<view class="praise-list">
			<view class="praise-item-container" v-for="(item, index) in filteredPraises" :key="item.id">
				<!-- 删除按钮 -->
				<view class="delete-btn" v-if="teacherSubjects.includes(item.subject)" @click="deletePraise(item.id)">
					<uni-icons type="trash" size="24" color="#fff"></uni-icons>
				</view>

				<!-- 表扬卡片 -->
				<view class="glass-card praise-item" :animation="itemAnim[index]"
					@touchstart="touchStart($event, item.id)" @touchmove="touchMove($event, item.id)"
					@touchend="touchEnd(item.id)" :style="{transform: `translateX(${item.translateX || 0}px)`}">
					<image :src="item.aver || '/static/aver1.jpg'" class="avatar"></image>
					<view class="praise-content">
						<view class="praise-header">
							<text class="student-name">{{ item.studentName }}</text>
							<text class="subject" :style="{backgroundColor: getSubjectColor(item.subject)}">
								{{ item.subject }} · {{ item.subjectDetail }}
							</text>
						</view>
						<view class="praise-footer">
							<text class="teacher">{{ item.teacherName }}</text>
							<text class="time">{{ formatTime(item.createTime) }}</text>
						</view>
						<view class="praise-marks" v-if="item.marks">
							<text>{{ item.marks }}</text>
						</view>
					</view>
				</view>
			</view>

			<view class="empty-tip" v-if="filteredPraises.length === 0">
				<image src="/static/images/empty.png" mode="aspectFit"></image>
				<text>这一天没有表扬记录哦~</text>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		globalVariable
	} from '../../configMy.js';
	export default {
		data() {
			return {
				teacher: {},
				teacherSubjects: [],
				activeDateIndex: 0,
				dateList: [],
				praiseList: [],
				dateCardAnim: [],
				itemAnim: [],
				touchStartX: 0, // 触摸开始X坐标
				currentTranslateX: 0, // 当前移动距离
				activeIndex: -1, // 当前激活的卡片索引
				touchStates: {}, // 改为使用对象存储每个卡片的触摸状态
				activeSwipeId: null // 当前激活滑动的卡片ID
			}
		},
		computed: {
			filteredPraises() {
				if (this.dateList.length === 0) return [];
				const selectedDate = this.dateList[this.activeDateIndex];
				// 为每个item添加translateX属性
				return this.praiseList.filter(item => {
					return item.createTime.includes(selectedDate);
				}).sort((a, b) => {
					return new Date(b.createTime) - new Date(a.createTime);
				}).map(item => {
					return {
						...item,
						translateX: item.translateX || 0
					}
				});
			},
			subjectColors() {
				return {
					'语文': '#FF9A9E', // 粉红
					'数学': '#A1C4FD', // 浅蓝
					'英语': '#FAC858', // 明黄
					'物理': '#91CB74', // 草绿
					'化学': '#FF8C66', // 橙红
					'生物': '#37BC9B', // 翠绿
					'地理': '#5D9CEC', // 天蓝
					'历史': '#DA4453', // 正红
					'政治': '#967ADC', // 紫罗兰
					'default': '#D3C1E5' // 默认浅紫
				}
			}
		},
		onLoad(options) {
			let that = this;
			uni.getStorage({
				key: 'teacher',
				success(res) {
					that.teacher = res.data;
					that.grade = options.grade
					// 从其他页面传递过来的数据
					if (options.praiseData) {
						that.praiseList = JSON.parse(decodeURIComponent(options.praiseData));
						that.initDates();
						that.initAnimations();
						//获取学科
						that.fetchTeacherSubjects();
					}
				}
			})

		},
		methods: {
			fetchTeacherSubjects() {
				uni.showLoading({
					title: '加载中...'
				});
				let that = this;
				uni.request({
					url: `${globalVariable}/getTeacherSubject?grade=${that.grade}&teacherId=${that.teacher.teacherId}`,
					success: (res) => {
						uni.hideLoading();
						if (res.data.status === 1) {
							// 保存教师教授的科目列表
							this.teacherSubjects = res.data.data.map(item => item.subject);

						} else {

						}
					},
					fail: (err) => {
						uni.hideLoading();

					}
				})
			},
			touchStart(e, id) {
				const item = this.praiseList.find(item => item.id === id);
				// 如果科目不在教师教授的科目列表中，不处理滑动
				if (!this.teacherSubjects.includes(item.subject)) return;
				// 如果有其他卡片处于滑动状态，先复位
				if (this.activeSwipeId && this.activeSwipeId !== id) {
					this.$set(this.praiseList.find(item => item.id === this.activeSwipeId), 'translateX', 0);
				}

				this.activeSwipeId = id;
				this.touchStates[id] = {
					startX: e.touches[0].clientX,
					startTime: Date.now()
				};
			},

			// 触摸移动
			touchMove(e, id) {
				const item = this.praiseList.find(item => item.id === id);
				// 如果科目不在教师教授的科目列表中，不处理滑动
				if (!this.teacherSubjects.includes(item.subject)) return;
				if (this.activeSwipeId !== id) return;

				const touchX = e.touches[0].clientX;
				const diffX = touchX - this.touchStates[id].startX;

				// 限制向右滑动
				if (diffX > 0) {
					this.$set(this.praiseList.find(item => item.id === id), 'translateX', 0);
					return;
				}

				// 限制最大左滑距离
				const maxLeft = -100;
				this.$set(this.praiseList.find(item => item.id === id), 'translateX', Math.max(diffX, maxLeft));
			},

			// 触摸结束
			touchEnd(id) {
				const item = this.praiseList.find(item => item.id === id);
				// 如果科目不在教师教授的科目列表中，不处理滑动
				if (!this.teacherSubjects.includes(item.subject)) return;
				if (this.activeSwipeId !== id) return;

				const currentX = this.praiseList.find(item => item.id === id).translateX;
				const threshold = -50;
				const velocity = Math.abs(currentX) / (Date.now() - this.touchStates[id].startTime);

				// 如果滑动距离超过阈值或快速滑动，保持打开状态
				if (currentX <= threshold || velocity > 0.3) {
					this.$set(this.praiseList.find(item => item.id === id), 'translateX', -80);
				} else {
					// 否则恢复原位
					this.$set(this.praiseList.find(item => item.id === id), 'translateX', 0);
					this.activeSwipeId = null;
				}

				delete this.touchStates[id];
			},
			// 删除表扬记录
			deletePraise(id) {
			  uni.showModal({
			    title: '提示',
			    content: '确定要删除这条表扬记录吗？',
			    success: (res) => {
			      if (res.confirm) {
			        // 正确的URL拼接方式
			        const url = `${globalVariable}/deleteParise?id=${id}`;
			        
			        uni.request({
			          url: url,
			          method: 'POST',
			          success: (res) => {
			            let info = res.data;
			            if(info.status == 1) {
			              // 从列表中移除已删除的项
			              this.praiseList = this.praiseList.filter(item => item.id !== id);
			              
			              uni.showToast({
			                title: '删除成功',
			                icon: 'success'
			              });
			              
			              this.activeSwipeId = null;
			            } else {
			              uni.showToast({
			                title: info.message || '删除失败',
			                icon: 'none'
			              });
			            }
			          },
			          fail: (err) => {
			            uni.showToast({
			              title: '网络错误，删除失败',
			              icon: 'none'
			            });
			            console.error('删除请求失败:', err);
			          }
			        });
			      } else {
			        // 取消删除，恢复原位
			        this.$set(this.praiseList.find(item => item.id === id), 'translateX', 0);
			        this.activeSwipeId = null;
			      }
			    }
			  });
			},
			// 其他方法保持不变...
			getSubjectColor(subject) {
				return this.subjectColors[subject] || this.subjectColors['default'];
			},
			initDates() {
				// 提取所有日期并去重
				const dates = this.praiseList.map(item => item.createTime.split(' ')[0]);
				const uniqueDates = [...new Set(dates)].sort((a, b) => new Date(b) - new Date(a));

				// 如果数据很多，只显示最近30天
				this.dateList = uniqueDates.slice(0, 30);

				// 如果没有数据，显示最近7天
				if (this.dateList.length === 0) {
					const today = new Date();
					for (let i = 0; i < 7; i++) {
						const date = new Date();
						date.setDate(today.getDate() - i);
						this.dateList.push(date.toISOString().split('T')[0]);
					}
				}
			},
			initAnimations() {
				// 初始化日期卡片动画
				this.dateCardAnim = this.dateList.map((_, index) => {
					return uni.createAnimation({
						duration: 600,
						delay: index * 100,
						timingFunction: 'ease-out'
					}).opacity(0).translateX(30).step().export();
				});

				// 初始化列表项动画
				this.itemAnim = this.praiseList.map((_, index) => {
					return uni.createAnimation({
						duration: 600,
						delay: index * 50,
						timingFunction: 'ease-out'
					}).opacity(0).translateY(20).step().export();
				});

				// 执行动画
				setTimeout(() => {
					this.dateCardAnim = this.dateList.map(() => {
						return uni.createAnimation({
							duration: 600,
							timingFunction: 'ease-out'
						}).opacity(1).translateX(0).step().export();
					});

					this.itemAnim = this.praiseList.map(() => {
						return uni.createAnimation({
							duration: 600,
							timingFunction: 'ease-out'
						}).opacity(1).translateY(0).step().export();
					});
				}, 300);
			},
			changeDate(index) {
				this.activeDateIndex = index;

				// 点击日期时的动画效果
				this.dateCardAnim = this.dateCardAnim.map((_, i) => {
					const anim = uni.createAnimation({
						duration: 300,
						timingFunction: 'ease-out'
					});

					if (i === index) {
						anim.scale(0.95).step({
							duration: 100
						});
						anim.scale(1).step({
							duration: 200
						});
					}

					return anim.export();
				});
			},
			formatDay(date) {
				return new Date(date).getDate();
			},
			formatWeekday(date) {
				const weekdays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
				return weekdays[new Date(date).getDay()];
			},
			formatDate(date) {
				const d = new Date(date);
				return `${d.getMonth() + 1}月${d.getDate()}日`;
			},
			formatTime(time) {
				if (!time) return '';
				const [date, t] = time.split(' ');
				return t.substring(0, 5);
			}
		}
	}
</script>

<style lang="scss" scoped>
	.praise-item-container {
		position: relative;
		margin-bottom: 20rpx;
		overflow: hidden;
		border-radius: 24rpx;
	}

	.delete-btn {
		position: absolute;
		right: 0;
		top: 0;
		bottom: 0;
		width: 80px;
		background-color: #ff5a5f;
		display: flex;
		align-items: center;
		justify-content: center;
		z-index: 1;
	}

	.praise-item {
		position: relative;
		z-index: 2;
		transition: transform 0.3s ease;
	}

	.history-container {
		padding: 30rpx;
		min-height: 100vh;
		background: linear-gradient(135deg, #f5f7fa 0%, #e4e8f0 100%);
		background-image:
			radial-gradient(circle at 10% 20%, rgba(255, 15, 51, 0.1) 0%, transparent 20%),
			radial-gradient(circle at 90% 80%, rgba(8, 255, 111, 0.1) 0%, transparent 20%);

		.header {
			margin-bottom: 40rpx;
			text-align: center;

			.title {
				display: block;
				font-size: 42rpx;
				font-weight: bold;
				color: #333;
				margin-bottom: 10rpx;
			}

			.subtitle {
				display: block;
				font-size: 26rpx;
				color: #888;
			}
		}

		/* 日期选择区域 */
		.date-scroll {
			white-space: nowrap;
			margin-bottom: 30rpx;
			padding: 10rpx 0;

			.date-cards {
				display: inline-flex;
				padding: 0 20rpx;
			}

			.date-card {
				display: inline-flex;
				flex-direction: column;
				align-items: center;
				justify-content: center;
				width: 120rpx;
				height: 150rpx;
				margin-right: 20rpx;
				border-radius: 20rpx;
				background: rgba(255, 255, 255, 0.4);
				backdrop-filter: blur(10px);
				-webkit-backdrop-filter: blur(10px);
				box-shadow: 0 8rpx 24rpx rgba(0, 0, 0, 0.05);
				transition: all 0.3s ease;

				&.active {
					background: rgba(255, 154, 158, 0.2);
					box-shadow: 0 8rpx 24rpx rgba(255, 154, 158, 0.2);

					.day {
						color: #FF9A9E;
						font-weight: bold;
					}

					.weekday,
					.date {
						color: #FF9A9E;
					}
				}

				.day {
					font-size: 48rpx;
					font-weight: bold;
					color: #333;
					margin-bottom: 6rpx;
					transition: all 0.3s ease;
				}

				.weekday {
					font-size: 24rpx;
					color: #999;
					margin-bottom: 4rpx;
					transition: all 0.3s ease;
				}

				.date {
					font-size: 22rpx;
					color: #999;
					transition: all 0.3s ease;
				}
			}
		}

		/* 表扬列表 */
		.praise-list {
			.praise-item {
				display: flex;
				padding: 30rpx;
				// margin-bottom: 20rpx;
				transition: all 0.3s ease;

				&:active {
					transform: scale(0.98);
				}

				.avatar {
					width: 80rpx;
					height: 80rpx;
					border-radius: 50%;
					background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
					display: flex;
					align-items: center;
					justify-content: center;
					color: white;
					font-size: 36rpx;
					font-weight: bold;
					margin-right: 20rpx;
					flex-shrink: 0;
				}

				.praise-content {
					flex: 1;

					.praise-header {
						display: flex;
						align-items: center;
						margin-bottom: 10rpx;

						.student-name {
							font-size: 30rpx;
							font-weight: bold;
							color: #333;
							margin-right: 20rpx;
						}

						.subject {
							font-size: 24rpx;
							color: #666;
							background: rgba(0, 0, 0, 0.05);
							padding: 4rpx 12rpx;
							border-radius: 20rpx;
						}
					}

					.praise-footer {
						display: flex;
						justify-content: space-between;

						.teacher,
						.time {
							font-size: 24rpx;
							color: #999;
						}
					}

					.praise-marks {
						margin-top: 10rpx;
						padding: 10rpx;
						background: rgba(0, 0, 0, 0.03);
						border-radius: 8rpx;
						font-size: 26rpx;
						color: #666;
					}
				}
			}

			.empty-tip {
				display: flex;
				flex-direction: column;
				align-items: center;
				justify-content: center;
				padding: 60rpx 0;
				text-align: center;

				image {
					width: 200rpx;
					height: 200rpx;
					margin-bottom: 20rpx;
					opacity: 0.6;
				}

				text {
					font-size: 28rpx;
					color: #999;
				}
			}
		}
	}

	/* 毛玻璃效果 */
	.glass-card {
		background: rgba(255, 255, 255, 0.6);
		backdrop-filter: blur(20px);
		-webkit-backdrop-filter: blur(20px);
		border-radius: 24rpx;
		box-shadow: 0 8rpx 24rpx rgba(0, 0, 0, 0.08);
		border: 1px solid rgba(255, 255, 255, 0.4);
	}
</style>